package com.rongke.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.mapper.CustServiceMapper;
import com.rongke.model.CustService;
import com.rongke.model.Muser;
import com.rongke.service.CustServiceService;

import com.rongke.service.MuserService;
import com.rongke.utils.HttpClientUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

/**
 * @version : Ver 1.0
 * @CustServiceController
 * @用户环信账户Controller
 */
@RestController
@RequestMapping(value = "/api/custService")
@Transactional
@CrossOrigin
public class CustServiceController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private CustServiceService custServiceService;
    @Autowired
    MuserService muserService;

    /**
     * @param custService
     * @return 返回值JsonResp
     * @添加用户环信账户
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addCustService(@RequestBody CustService custService) {
        log.debug("添加用户环信账户");
        custService.setGmtDatetime(new Date());
        custServiceService.insert(custService);
        return JsonResp.ok(custService);
    }

    /**
     * @param custService
     * @return 返回值JsonResp
     * @修改用户环信账户
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateCustService(@RequestBody CustService custService) {
        log.debug("修改用户环信账户");
        custServiceService.updateById(custService);
        return JsonResp.ok(custService);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找用户环信账户
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectCustService(Long id) {
        log.debug("查找用户环信账户");
        CustService custService = custServiceService.selectById(id);
        return JsonResp.ok(custService);
    }

    /**
     * @param custService
     * @return 返回值JsonResp
     * @根据条件查找用户环信账户
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectCustServiceByCondition(@RequestBody CustService custService) {
        log.debug("根据条件查找用户环信账户");
        if (custService == null)
            return JsonResp.toFail("参数不能为空");
        List<CustService> custServiceList = custServiceService.selectByCondition(custService);
        return JsonResp.ok(custServiceList);
    }

    /**
     * 获取某用户的环信客服账户,没有则创建一个
     *
     * @param muserId
     * @return
     */
    @RequestMapping(value = "/getCustServiceAccountByMuserId", method = RequestMethod.GET)
    public JsonResp getCustServiceAccountByMuserId(Long muserId) {
        log.debug("获取某用户的环信客服账户,没有则创建一个");
        if (null == muserId) {
            return JsonResp.ok("muserId参数不能为空");
        }
        EntityWrapper<CustService> ew = new EntityWrapper<>();
        ew.eq("muser_id", muserId);
        CustService cs = custServiceService.selectOne(ew);
        if (null != cs) {
            return JsonResp.ok(cs);
        } else {
            Muser muser = muserService.selectById(muserId);
            String nickname=muser.getUserName();
            String username = muser.getPhone();
            String password = "123456";
//            String password = muser.getPassword();
            CustService cus=new CustService();
            cus.setMuserId(muserId);
            cus.setUsername(username);
            cus.setPassword(password);
            cus.setGmtDatetime(new Date());
            custServiceService.insert(cus);
            JsonResp returnJson = registerCustService(username, password,nickname);
            return returnJson;
        }
    }


    /**
     * 注册环信客服账号
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/registerCustService", method = RequestMethod.GET)
    public JsonResp registerCustService(String username, String password,String nickname) {
        log.debug("注册环信客服账号");
        String token = getCustServiceToken();
        String url = "http://a1-vip5.easemob.com/1421171009061345/kefuchannelapp45074/users";
        String postBody = "[\n" +
                "    {\n" +
                "        \"username\": \"" + username + "\",\n" +
                "        \"password\": \"" + password + "\",\n" +
                "        \"nickname\": \"" + nickname + "\"\n" +
                "    }\n" +
                "]";
        String charset = "UTF-8";
        String mimeType = "application/json";
        HttpClient client = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization", "Bearer " + token);
        HttpEntity entity = new StringEntity(postBody, ContentType.create(mimeType, charset));
        httpPost.setEntity(entity);
        HttpResponse res;
        String result1 = "";
        try {
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(128);
            cm.setDefaultMaxPerRoute(128);
            client = HttpClients.custom().setConnectionManager(cm).build();
            res = client.execute(httpPost);
            result1 = IOUtils.toString(res.getEntity().getContent(), charset);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            httpPost.releaseConnection();
        }
//        String result = HttpClientUtil.sendPostSSLRequest(url, postBody, charset, mimeType);
        JSONObject obj = (JSONObject) JSON.parse(result1);
        return JsonResp.ok(obj);
    }

    /**
     * 获取当前token
     *
     * @return
     */
    @RequestMapping(value = "/getCustServiceToken", method = RequestMethod.GET)
    public String getCustServiceToken() {
        String url = "http://a1-vip5.easemob.com/1421171009061345/kefuchannelapp45074/token";
        String postBody = "{\n" +
                "    \"grant_type\": \"client_credentials\",\n" +
                "    \"client_id\": \"YXA6P5ClUKy9EeeUzC32KSmmiQ\",\n" +
                "    \"client_secret\": \"YXA6glDC5-BHgQP4wM-tcGxFIzpyP8Y\"\n" +
                "}";
        String charset = "UTF-8";
        String mimeType = "application/json";
        String result = HttpClientUtil.sendPostSSLRequest(url, postBody, charset, mimeType);
        JSONObject obj = (JSONObject) JSON.parse(result);
        String token = obj.getString("access_token");
        return token;
    }
}
